package com.cloud.annex.mapper;

import cn.hutool.core.util.ZipUtil;
import com.cloud.common.utils.PolicyJsonUtils;
import com.cloud.utils.ServletUtils;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Minio 文件存储工具
 *
 * @author yzj
 */
@Component
public class MinioMapper {

    @Autowired
    private MinioClient minioClient;

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public boolean bucketExists(String bucketName) {
        boolean flag = false;
        try {
            flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            return true;
        }
        return false;
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    public boolean makeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        try {
            if (!flag) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 设置桶策略,可读可写等等
     *
     * @param bucketName 存储桶名称
     */
    public boolean setBucketPolicy(String bucketName) {
        try {
            String policy = PolicyJsonUtils.JsonToString("policyJson.json", bucketName);
            // 用工具类 就是把里面的常量替换出来就可以了
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policy).build());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 列出所有存储桶名称
     *
     * @return
     */
    public List<String> listBucketNames() {
        List<Bucket> bucketList = listBuckets();
        List<String> bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }

    /**
     * 列出所有存储桶
     *
     * @return
     */
    public List<Bucket> listBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除存储桶
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public boolean removeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                Iterable<Result<Item>> myObjects = listObjects(bucketName);
                for (Result<Item> result : myObjects) {
                    Item item = result.get();
                    // 有对象文件,则删除失败
                    if (item.size() > 0) {
                        return false;
                    }
                }
                // 删除存储桶,注意,只有存储桶为空时才能删除成功。
                minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
                flag = bucketExists(bucketName);
                if (!flag) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public List<String> listObjectNames(String bucketName) {
        List<String> listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                Iterable<Result<Item>> myObjects = listObjects(bucketName);
                for (Result<Item> result : myObjects) {
                    Item item = result.get();
                    listObjectNames.add(item.objectName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listObjectNames;
    }

    /**
     * 列出存储桶中的所有对象
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public Iterable<Result<Item>> listObjects(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        }
        return null;
    }

    /**
     * 列出存储桶中指定前缀的所有对象
     *
     * @param bucketName 存储桶名称
     * @param preFix     前缀
     * @return
     */
    public Iterable<Result<Item>> listObjects(String bucketName, String preFix) {
        boolean flag = bucketExists(bucketName);
        if (flag && null != preFix) {
            return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(preFix).build());
        }
        return null;
    }

    /**
     * 通过文件上传到对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return
     */
    public boolean uploadObject(String bucketName, String objectName, String fileName) {
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucketName)
                        .object(objectName).filename(fileName).build());
                ObjectStat statObject = statObject(bucketName, objectName);
                if (statObject != null && statObject.length() > 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 文件上传
     *
     * @param bucketName    存储桶名称
     * @param multipartFile annex 对象
     * @param fileName      文件名称
     */
    public void putObject(String bucketName, MultipartFile multipartFile, String fileName) {
        try {
            PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(),
                    PutObjectOptions.MIN_MULTIPART_SIZE);
            putObjectOptions.setContentType(multipartFile.getContentType());
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType()).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过InputStream 上传对象
     *
     * @param bucketName  存储桶名称
     * @param objectName  存储桶里的对象名称
     * @param inputStream 要上传的流
     * @param contentType 上传的文件类型 例如 video/mp4  image/jpg
     * @return
     */
    public boolean putObject(String bucketName, String objectName, InputStream inputStream, String contentType) {
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                // 不清楚文件的大小时，可以传-1，10485760。如果知道大小也可以传入size，partsize。
                minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName)
                        .stream(inputStream, -1, 10485760)
                        .contentType(contentType).build());
                ObjectStat statObject = statObject(bucketName, objectName);
                if (statObject != null && statObject.length() > 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    public InputStream getObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                ObjectStat statObject = statObject(bucketName, objectName);
                if (statObject != null && statObject.length() > 0) {
                    InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                            .bucket(bucketName).object(objectName).build());
                    return stream;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param offset     起始字节的位置
     * @param length     要读取的长度 (可选,如果无值则代表读到文件结尾)
     * @return
     */
    public InputStream getObject(String bucketName, String objectName, long offset, Long length) {
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                ObjectStat statObject = statObject(bucketName, objectName);
                if (statObject != null && statObject.length() > 0) {
                    InputStream stream = minioClient.getObject(GetObjectArgs.builder()
                            .bucket(bucketName).object(objectName).offset(1024L).length(4096L).build());
                    return stream;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载并将文件保存到本地
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return
     */
    public boolean downloadObject(String bucketName, String objectName, String fileName) {
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                ObjectStat statObject = statObject(bucketName, objectName);
                if (statObject != null && statObject.length() > 0) {
                    minioClient.downloadObject(DownloadObjectArgs.builder()
                            .bucket(bucketName).object(objectName).filename(fileName).build());
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除一个对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     */
    public boolean removeObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
     *
     * @param bucketName  存储桶名称
     * @param objectNames 含有要删除的多个object名称的迭代器对象
     * @return eg:
     * List<DeleteObject> objects = new LinkedList<>();
     * objects.add(new DeleteObject("my-objectname1"));
     * objects.add(new DeleteObject("my-objectname2"));
     * objects.add(new DeleteObject("my-objectname3"));
     */
    public List<String> removeObjects(String bucketName, List<DeleteObject> objectNames) {
        List<String> deleteErrorNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        try {
            if (flag) {
                Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder()
                        .bucket(bucketName).objects(objectNames).build());
                for (Result<DeleteError> result : results) {
                    DeleteError error = result.get();
                    deleteErrorNames.add(error.objectName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deleteErrorNames;
    }

    /**
     * 生成一个给HTTP GET请求用的Presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个Presigned URL可以设置一个失效时间,默认值是7天。
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间（以天为单位）
     * @return
     */
    public String getPreSignObjectUrl(String bucketName, String objectName, Integer expires) {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            try {
                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET).bucket(bucketName).object(objectName)
                        .expiry(expires, TimeUnit.DAYS)         // 按天传参
//                        .expiry(24 * 60 * 60)                 // 用秒来计算一天时间有效期
//                        .expiry(expires, TimeUnit.HOURS)      // 按小时传参数
                        .build());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return url;
    }

    /**
     * 生成一个给HTTP PUT请求用的Presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。
     * 这个Presigned URL可以设置一个失效时间,默认值是7天。
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间（以天为单位）
     * @return
     */
    public String putPreSignObject(String bucketName, String objectName, Integer expires) {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            try {
                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .method(Method.PUT).bucket(bucketName).object(objectName)
                        .expiry(expires, TimeUnit.DAYS)     // 按天传参
//                        .expiry(24 * 60 * 60)             // 用秒来计算一天时间有效期
//                        .expiry(1, TimeUnit.HOURS)        // 按小时传参数
                        .build());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return url;
    }

    /**
     * 获取对象的元数据
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    public ObjectStat statObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = null;
            try {
                statObject = minioClient.statObject(StatObjectArgs.builder()
                        .bucket(bucketName).object(objectName).build());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return statObject;
        }
        return null;
    }

    /**
     * 文件访问路径
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    public String getObjectUrl(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            try {
                url = minioClient.getObjectUrl(bucketName, objectName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return url;
    }

    /**
     * 文件下载
     *
     * @param bucketName   存储桶名称
     * @param fileName
     * @param originalName
     * @param response
     */
    public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
        try {
            InputStream file = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName).object(fileName).build());
            fileName = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StringUtils.isNotEmpty(originalName)) {
                fileName = originalName;
            }
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            ServletUtils.writeIO(file, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 多文件下载
     *
     * @param bucketName 存储桶名称
     * @param zipName    压缩文件名称
     * @param urlList
     * @param response
     */
    public void downloadFiles(String bucketName, String zipName, List<String> urlList, HttpServletResponse response) {
        try {
            InputStream[] files = new InputStream[urlList.size()];
            // 被压缩文件名称
            String[] srcFileNames = new String[urlList.size()];
            for (int i = 0; i < urlList.size(); i++) {
                String fileUrl = urlList.get(i);
                InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                        .bucket(bucketName).object(fileUrl).build());
                if (inputStream == null) {
                    continue;
                }
                files[i] = inputStream;
                String[] splitFileUrl = fileUrl.split("/");
                srcFileNames[i] = splitFileUrl[splitFileUrl.length - 1];
            }
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(zipName + ".zip", "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            //多个文件压缩成压缩包返回
            ZipUtil.zip(outputStream, srcFileNames, files);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
